package net.jblog.business.dao.impl;

import java.util.logging.Logger;

import javax.jdo.PersistenceManager;

import net.jblog.business.dao.AdministratorUserDao;
import net.jblog.data.factory.DataManagerFactory;
import net.jblog.data.model.AdministratorUser;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Query;

public class AdministratorUserDaoImpl implements AdministratorUserDao {
	private Logger log = Logger.getLogger(AdministratorUserDaoImpl.class.getName());
	
	@Override
	public AdministratorUser findByEmailPassword(String email, String password) {
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

		// The Query interface assembles a query
		Query q = new Query(AdministratorUser.class.getSimpleName());
		q.addFilter("email", Query.FilterOperator.EQUAL, email);
		q.addFilter("password", Query.FilterOperator.EQUAL, password);

		Entity entity = datastore.prepare(q).asSingleEntity();
		return copyProperties(entity);
	}

	@Override
	public void persist(AdministratorUser entity) {
		PersistenceManager pm = DataManagerFactory.get().getPersistenceManager();
		
        try {
            pm.makePersistent(entity);
            log.info("Enregistrement d'un administrateur");
        } finally {
            pm.close();
        }

	}
	
	private AdministratorUser copyProperties(Entity entity) {
		if(entity != null) {
			AdministratorUser user = new AdministratorUser();
			user.setKey(entity.getKey());
			user.setEmail(entity.getProperty("email").toString());
			user.setScreenName(entity.getProperty("screenName").toString());
			user.setPassword(entity.getProperty("password").toString());
			return user;
		}
		return null;
	}

}
